﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
// add
using System.Net;
using System.Net.Sockets;
using System.IO;
using FormBaseLib;

namespace FormBase
{
    public partial class FPGM0050 : Form
    {
        //CProject mProject = Program.gProject;
        string msScanned = string.Empty;
        string msBarcode = string.Empty;
        bool mbBarcodeShowing = false;

        //CAction mAction = new CAction("FPGM0050");
        CAction mAction = new CAction();

        Socket mSocket = null;

        byte[] mbaReceive;
        string msVersion;
        delegate void ShowMsgEventHandler(string sMsg, Color color1);

        public FPGM0050()
        {
            InitializeComponent();
        }

        private void FPGM0050_Load(object sender, EventArgs e)
        {
            Text = "TCP Client template";
            KeyPreview = true;


            myClear();

            myDefaultValues();
            
        }



        private void myClear()
        {
            txtBarcode.Clear();
            txtMsg.Clear();
            txtHex.Clear();
            txtLength.Clear();
            ActiveControl = txtBarcode;
        }
        private void myClose()
        {
            Close();
        }



        private void myShowFound()
        {
            mbBarcodeShowing = true;
            myClear();
            txtBarcode.Text = msBarcode;
            txtLength.Text = msScanned.Length.ToString();
            txtHex.Text = CProject.gStringASCToHex(msScanned);
            txtMsg.Text = "Success.";
        }
        private void myShowNotFound()
        {
            mbBarcodeShowing = true;
            myClear();
            txtBarcode.Text = msBarcode;
            txtLength.Text = msScanned.Length.ToString();
            txtHex.Text = CProject.gStringASCToHex(msScanned);
            txtMsg.Text = "Success scanned but not found in DB.";
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
        private string myGetBarcode(string sInput)
        {
            string s1;

            s1 = CProject.gCRLFRemove(sInput);
            return s1;

        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            myClear();

        }


        private void FPGM0030_KeyPress(object sender, KeyPressEventArgs e)
        {
            string s1 = string.Empty;
            char cInputKeyPress = e.KeyChar;
            switch (cInputKeyPress)
            {
                case (char)Keys.Escape:
                    DialogResult d1 = MessageBox.Show("Close ?" + s1, "Confirm", MessageBoxButtons.OKCancel);
                    if (d1 == DialogResult.OK)
                    {
                        //CProject.End();
                        this.Close();
                    }
                    break;
                case (char)Keys.LineFeed:
                    CProject.mApp.mAction.AppendMsgDebug("FPGM0020.KeyPress().Enter");
                    msScanned = msScanned + ((char)Keys.LineFeed);
                    CProject.mApp.mAction.AppendMsgDebug("msBarcodeScanned=" + msScanned);
                    Boolean bFound = false;
                    //txtHex.Text = mProject.StringASCToHex(msScanned);
                    msBarcode = myGetBarcode(msScanned);
                    if (msBarcode.Length < 1)
                    {
                        e.Handled = true;
                        return;
                    }
                    //txtBarcode.Text = msBarcode;
                    switch (msBarcode)
                    {
                        case "T": // Test
                            bFound = true;
                            msBarcode = "Test";
                            break;
                        case "V": // Version
                            bFound = true;
                            msBarcode = CProject.mApp.msAssemblyVersion;
                            break;
                        case "7192751043689":
                            bFound = true;
                            break;
                        case "ABCDEFGH":
                            bFound = true;
                            break;
                    }
                    if (bFound)
                        myShowFound();
                    else
                        myShowNotFound();

                    msScanned = string.Empty;
                    //e.Handled = true;
                    break;

                case (char)Keys.F1:
                    // KeyPrress抓不到F1, 改用輸入VERSION字串處理.
                    //MessageBox.Show(String.Format("Version {0}", Assembly.GetExecutingAssembly().GetName().Version.ToString()), "Information");
                    CProject.mApp.PopupMsg(CProject.mApp.msAssemblyVersion);
                    //e.Handled = true;
                    break;
                default:
                    msScanned += cInputKeyPress;
                    //e.Handled = true;
                    break;
            }
            e.Handled = true;

        }

        private void FPGM0030_FormClosing(object sender, FormClosingEventArgs e)
        {
            // release any open resources.

        }

        private void btnDefaultRS232_Click(object sender, EventArgs e)
        {
            myDefaultValues();
        }


        private void btnConnect_Click(object sender, EventArgs e)
        {
            myConnect();
        }

        private void myConnect()
        {
            TcpClient mClient = new TcpClient();
            Stream mStream = null;

            //ref: http://stackoverflow.com/questions/11617523/how-do-i-re-use-tcp-client
            // ref: http://stackoverflow.com/questions/6127419/faster-way-to-communicate-using-tcpclient
            // ref: http://stackoverflow.com/questions/14252182/how-to-use-tcp-client-listener-in-multithreaded-c
            // ref: 
            
            string sServer;
            int iPort;
            // todo: IPAddress ip1 = new IPEndPoint(
            sServer = txtServerIP.Text;

            if (Dns.GetHostEntry(sServer) == null)
            {
                CProject.mApp.mAction.AppendMsgDebug("Can't find server: " + sServer);
                return;
            }

            try
            {
                if (int.TryParse(txtPort.Text, out iPort) == false)
                {
                    CProject.mApp.PopupError("Wrong port");
                    return;
                }

                //mClient.Connect(sServer, 8100);
                mClient.Connect(sServer, iPort);
            }
            catch (SocketException exc)
            {
                CProject.mApp.mAction.AppendMsgDebug(string.Format("Cannot connect to {0}: {1}.", sServer, exc.Message)); 
            }

            byte[] baRead = new byte[32];
            int bytes = 0;
            string time = null;
            try
            {
                mStream = mClient.GetStream();

                bytes = mStream.Read(baRead, 0, baRead.Length);
                time = Encoding.ASCII.GetString(baRead);
            }
            catch (InvalidOperationException exc)
            {
                CProject.mApp.mAction.AppendMsgDebug(string.Format("Cannot connect to {0}: {1}.", sServer, exc.Message)); 
            }
            finally
            {
                if (mClient != null)
                    mClient.Close();

                if (mStream != null)
                    mStream.Close();
            }

            txtBarcode.Text = string.Format("Current date and time is: {0}", time);
            txtMsg.Text = string.Format("Received {0} bytes.", bytes);


        }
        private void OnShowMsg(string sMsg, Color color1)
        {
            lblStatus.Text = sMsg;
            if (lblStatus.ForeColor != color1)
                lblStatus.ForeColor = color1;
        }


        private void myGetVersion()
        {
        }

        public void ShowMsg(string sMsg)
        {
            Invoke(new ShowMsgEventHandler(OnShowMsg), new object[] { sMsg, SystemColors.ControlText });
        }
        public void ShowMsgError(string sMsg)
        {
            Invoke(new ShowMsgEventHandler(OnShowMsg), new object[] { sMsg, Color.Red });
        }
        private void myChecksumn(byte[] baInput)
        {
            int iChecksum;
            int iCmdLength = 10;
            if (baInput.Length < 14)
            {
                ShowMsgError("Length must be 14");
                return;
            }
            iChecksum = 0;
            for (int i = 0; i < iCmdLength; i++)
                iChecksum = iChecksum + (baInput[i] * (iCmdLength - i));

            if (iChecksum != 1773)
            {
                ShowMsgError("Checksum = " + iChecksum.ToString());
                return;
            }
            CBit.CopyToByteArray(iChecksum, baInput, 10);
            ShowMsg("Checksum ok!");
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            myDisconnect();
        }
        private void myDisconnect()
        {
            lblConnected.Text = string.Empty;
            ShowMsg("Disconnect");
        }

        private void btnGetVersion_Click(object sender, EventArgs e)
        {
            myGetVersion();
        }

        private void btnConnect_Click_1(object sender, EventArgs e)
        {
            myConnect();
        }

        private void btnDefaultRS232_Click_1(object sender, EventArgs e)
        {
            myDefaultValues();
        }
        private void myDefaultValues()
        {
            txtServerIP.Text = "127.0.0.1";
            txtPort.Text = "8013";
        }

        private void btnDisconnect_Click_1(object sender, EventArgs e)
        {

        }


    }
}
